package com.llkj.qingnianguoxue.view;

import android.Manifest;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.graphics.Point;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresPermission;
import android.support.design.widget.AppBarLayout;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.Display;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.llkj.qingnianguoxue.R;
import com.llkj.qingnianguoxue.base.ConstantUserInfo;
import com.llkj.qingnianguoxue.base.MyApplication;
import com.llkj.qingnianguoxue.bean.HotRankingBean;
import com.llkj.qingnianguoxue.db.BookList;
import com.llkj.qingnianguoxue.http.AnsynHttpRequest;
import com.llkj.qingnianguoxue.http.HttpMethod;
import com.llkj.qingnianguoxue.mine.BalanceActivity;
import com.llkj.qingnianguoxue.mine.PayOrderActivity;
import com.llkj.qingnianguoxue.util.DialogUtil;
import com.llkj.qingnianguoxue.util.PayMethodViewUtil;
import com.llkj.qingnianguoxue.util.StringUtils;
import com.llkj.qingnianguoxue.util.SystemBarTintManager;
import com.llkj.qingnianguoxue.util.ToastUtil;
import com.llkj.qingnianguoxue.util.Utils;
import com.pingplusplus.android.Pingpp;
import com.tbruyelle.rxpermissions.RxPermissions;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.FileCallBack;

import org.litepal.crud.DataSupport;

import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;
import rx.functions.Action1;

import static com.llkj.qingnianguoxue.mine.PayOrderActivity.REQUEST_ORDER_PAY;

/**
 * Created by Administrator on 2016/7/15 0015.
 */
public class ReadActivity extends BaseActivity{
    public static final int REQUEST_READ_BOOK_CODE = 6099;
    private static final String TAG = "ReadActivity";
    private int FONT_SIZE_MIN;
    private int FONT_SIZE_MAX;
    private int currentFontSize;

    @BindView(R.id.bookpage)
    PageWidget bookpage;
    @BindView(R.id.rl_bottom)
    RelativeLayout rl_bottom;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.appbar)
    AppBarLayout appbar;
    @BindView(R.id.tv_dark)
    ImageView tv_dark;
    @BindView(R.id.sb_brightness)
    SeekBar sb_brightness;
    @BindView(R.id.tv_bright)
    ImageView tv_bright;
    @BindView(R.id.tv_subtract)
    TextView tv_subtract;
    @BindView(R.id.tv_add)
    TextView tv_add;

    private Config config;
    private WindowManager.LayoutParams lp;
    private BookList bookList;
    private PageFactory pageFactory;
    private int screenWidth, screenHeight;
    // popwindow是否显示
    private Boolean isShow = false;
    private boolean isSpeaking = false;
    private Boolean isSystem;

    // 接收电池信息更新的广播
    private BroadcastReceiver myReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(Intent.ACTION_BATTERY_CHANGED)) {
                Log.e(TAG, Intent.ACTION_BATTERY_CHANGED);
                int level = intent.getIntExtra("level", 0);
                pageFactory.updateBattery(level);
            } else if (intent.getAction().equals(Intent.ACTION_TIME_TICK)) {
                Log.e(TAG, Intent.ACTION_TIME_TICK);
                pageFactory.updateTime();
            }
        }
    };
    private Boolean isPermissions;
    private Dialog waitDialog;
    /**
     * 图书下载路径
     */
    private String bookUrl;
    /**
     * 图书名字
     */
    private String bookName;//图书标题
    private String bookId;
    private String bookDesc;//图书简介
    private String bookCoverUrl;//图书封面url
    private long begin;
    private String percent;
    private long mStartTime;
    private Dialog mDialogFree;
    private int mIsBuy = 1;
    private String mPayMoney;//支付金额

    @Override
    public int getLayoutRes() {
        return R.layout.activity_read;
    }

    @Override
    protected void initData() {
        if (Build.VERSION.SDK_INT >= 14 && Build.VERSION.SDK_INT < 19) {
            bookpage.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        }
        mStartTime = System.currentTimeMillis();

        FONT_SIZE_MIN = (int) this.getResources().getDimension(R.dimen.reading_min_text_size);
        FONT_SIZE_MAX = (int) this.getResources().getDimension(R.dimen.reading_max_text_size);
        bookUrl = getIntent().getStringExtra("bookurl");
        bookName = getIntent().getStringExtra("bookname");
        bookId = getIntent().getStringExtra("bookid");
        bookDesc = getIntent().getStringExtra("bookDesc");
        bookCoverUrl = getIntent().getStringExtra("bookCoverUrl");
        if (TextUtils.isEmpty(getIntent().getStringExtra("bookbegin"))) {
            begin = 0;
        }else {
            begin = Long.valueOf(getIntent().getStringExtra("bookbegin"));
        }
        mIsBuy = getIntent().getIntExtra("isBuy",mIsBuy);
        mPayMoney = getIntent().getStringExtra("payMoney");

        toolbar.setTitle(bookName);
        setSupportActionBar(toolbar);
        toolbar.setNavigationIcon(R.drawable.icon_back_white);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        new RxPermissions(this)
                .request(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE)
                .subscribe(new Action1<Boolean>() {
                    @Override
                    public void call(Boolean aBoolean) {
                        isPermissions = aBoolean;
                    }
                });

        config = Config.getInstance();
        pageFactory = PageFactory.getInstance();

        IntentFilter mfilter = new IntentFilter();
        mfilter.addAction(Intent.ACTION_BATTERY_CHANGED);
        mfilter.addAction(Intent.ACTION_TIME_TICK);
        registerReceiver(myReceiver, mfilter);

        //获取屏幕宽高
        WindowManager manage = getWindowManager();
        Display display = manage.getDefaultDisplay();
        Point displaysize = new Point();
        display.getSize(displaysize);
        screenWidth = displaysize.x;
        screenHeight = displaysize.y;
        //保持屏幕常亮
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        //隐藏
        hideSystemUI();
        //改变屏幕亮度
        if (!config.isSystemLight()) {
            BrightnessUtil.setBrightness(this, config.getLight());
        }
        bookpage.setPageMode(config.getPageMode());
        pageFactory.setPageWidget(bookpage);
        //下载文件或者从数据库中取
        downFile();
        initSetting();
    }

    /**
     * 处理试读
     */
    private void freeReading(float readProgress){
        if(mIsBuy!=1 && readProgress*100>=2){//如果没有购买，处理试读,小于2%
            if(mDialogFree!=null && mDialogFree.isShowing()){
                return;
            }
            mDialogFree = DialogUtil.dialogConfirm(this, "是否感兴趣?\n如果继续阅读请付费购买",null,null,"立即购买",new DialogUtil.DialogClickListener() {
                @Override
                public void dialogClick(int type) {
                    if(type==1){//购买
                        startPay();
                    }else{//不购买
                        ReadActivity.this.finish();
                    }
                }
            });
            mDialogFree.setCanceledOnTouchOutside(false);
            mDialogFree.setOnKeyListener(new DialogInterface.OnKeyListener() {
                @Override
                public boolean onKey(DialogInterface dialogInterface, int i, KeyEvent keyEvent) {
                    if(keyEvent.getKeyCode()== KeyEvent.KEYCODE_BACK){
                        ReadActivity.this.finish();
                    }
                    return false;
                }
            });
            mDialogFree.show();
        }
    }

    private void initSetting() {
        //初始化亮度
        isSystem = config.isSystemLight();
        setBrightness(config.getLight());

        //初始化字体大小
        currentFontSize = (int) config.getFontSize();

        sb_brightness.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (progress > 10) {
                    changeBright(false, progress);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {}

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {}
        });
    }

    //设置亮度
    public void setBrightness(float brightness) {
        sb_brightness.setProgress((int) (brightness * 100));
    }


    private void downFile() {
        if (!isPermissions) {
            ToastUtil.makeLongText(this, "对不起，没有获取到读取文件权限");
            return;
        }
        List<BookList> books = DataSupport.where("bookname = ?", bookName).find(BookList.class);
        if (books != null && books.size() != 0) {
            try {
                pageFactory.openBook(books.get(0));
            } catch (IOException e) {
                e.printStackTrace();
                Toast.makeText(this, "打开电子书失败", Toast.LENGTH_SHORT).show();
            }
            return;
        }

        loadWaitDialog();
        OkHttpUtils//
                .get()//
                .url(bookUrl)//
                .build()//
                .execute(new FileCallBack(Environment.getExternalStorageDirectory().getAbsolutePath(), bookName) {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        dismissWaitDialog();
                        ToastUtil.makeLongText(ReadActivity.this, "对不起，图书加载失败");
                    }

                    @Override
                    public void onResponse(File file, int id) {
                        dismissWaitDialog();
                        if (file != null && file.exists() && file.isFile()) {
                            final List<BookList> bookLists = new ArrayList<BookList>();
                            BookList bookList = new BookList();
                            String bookName = Fileutil.getFileNameNoEx(file.getName());
                            bookList.setBookname(bookName);
                            bookList.setBookpath(file.getAbsolutePath());
                            bookList.setId(Integer.valueOf(bookId));
                            bookList.setBegin(begin);
                            bookLists.add(bookList);
                            Executors.newFixedThreadPool(3).execute(new Runnable() {
                                @Override
                                public void run() {
                                    DataSupport.saveAll(bookLists);
                                }
                            });
                            try {
                                pageFactory.openBook(bookList);
                            } catch (IOException e) {
                                e.printStackTrace();
                                Toast.makeText(ReadActivity.this, "打开电子书失败",
                                        Toast.LENGTH_SHORT).show();
                            }
                        } else {
                            dismissWaitDialog();
                            ToastUtil.makeLongText(ReadActivity.this, "对不起，图书加载失败");
                        }
                    }
                });
    }


    /**
     * 全局等待对话框
     */
    public void loadWaitDialog() {
        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                initWaitDialog();
            }
        });
    }

    private void initWaitDialog() {
        if (waitDialog == null || !waitDialog.isShowing()) {
            View view = LayoutInflater.from(this).inflate(R.layout.dialog_load_wait, null);
            waitDialog = DialogUtil.getDialog(this, view);
            waitDialog.setCanceledOnTouchOutside(false);
            waitDialog.show();
        }
    }

    public void dismissWaitDialog() {
        try {
            this.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (waitDialog != null && waitDialog.isShowing()) {
                        waitDialog.dismiss();
                        waitDialog = null;
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void initListener() {

        pageFactory.setPageEvent(new PageFactory.PageEvent() {
            @Override
            public void changeProgress(float progress) {
                begin = pageFactory.getCurrentPage().getBegin();
                DecimalFormat decimalFormat = new DecimalFormat("0.00");//构造方法的字符格式这里如果小数不足2位,会以0补足.
                //format 返回的是字符串
                percent = decimalFormat.format(progress * 100.0)+"%";
                Log.e(TAG, "begin: " + begin);
                Log.e(TAG, "progress: " + progress);
                freeReading(progress);
            }
        });

        bookpage.setTouchListener(new PageWidget.TouchListener() {
            @Override
            public void center() {
                if (isShow) {
                    hideReadSetting();
                } else {
                    showReadSetting();
                }
            }

            @Override
            public Boolean prePage() {
                if (isShow || isSpeaking) {
                    return false;
                }

                pageFactory.prePage();
                if (pageFactory.isfirstPage()) {
                    return false;
                }

                return true;
            }

            @Override
            public Boolean nextPage() {
                Log.e("setTouchListener", "nextPage");
                if (isShow || isSpeaking) {
                    return false;
                }

                pageFactory.nextPage();
                if (pageFactory.islastPage()) {
                    return false;
                }
                return true;
            }

            @Override
            public void cancel() {
                pageFactory.cancelPage();
            }
        });

    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!isShow) {
            hideSystemUI();
        }

    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        pageFactory.clear();
        bookpage = null;
        unregisterReceiver(myReceiver);
        isSpeaking = false;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (isShow) {
                hideReadSetting();
                return true;
            }
            onBackPressed();
            finish();
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 隐藏菜单。沉浸式阅读
     */
    private void hideSystemUI() {
        // Set the IMMERSIVE flag.
        // Set the content to appear under the system bars so that the content
        // doesn't resize when the system bars hide and show.
        getWindow().getDecorView().setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                        | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                        | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                        //  | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hide nav bar
                        | View.SYSTEM_UI_FLAG_FULLSCREEN // hide status bar
                        | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
        );
    }

    private void showSystemUI() {
        getWindow().getDecorView().setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_LAYOUT_STABLE
//                        | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                        | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                        | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
        );
    }

    private void showReadSetting() {
        isShow = true;
        if (isSpeaking) {
            Animation topAnim = AnimationUtils.loadAnimation(this, R.anim.dialog_top_enter);
        } else {
            showSystemUI();

            Animation bottomAnim = AnimationUtils.loadAnimation(this, R.anim.dialog_enter);
            Animation topAnim = AnimationUtils.loadAnimation(this, R.anim.dialog_top_enter);
            rl_bottom.startAnimation(topAnim);
            appbar.startAnimation(topAnim);
//        ll_top.startAnimation(topAnim);
            rl_bottom.setVisibility(View.VISIBLE);
//        ll_top.setVisibility(View.VISIBLE);
            appbar.setVisibility(View.VISIBLE);
        }
    }

    private void hideReadSetting() {
        isShow = false;
        Animation bottomAnim = AnimationUtils.loadAnimation(this, R.anim.dialog_exit);
        Animation topAnim = AnimationUtils.loadAnimation(this, R.anim.dialog_top_exit);
        if (rl_bottom.getVisibility() == View.VISIBLE) {
            rl_bottom.startAnimation(topAnim);
        }
        if (appbar.getVisibility() == View.VISIBLE) {
            appbar.startAnimation(topAnim);
        }
        rl_bottom.setVisibility(View.GONE);
        appbar.setVisibility(View.GONE);
        hideSystemUI();
    }


    @OnClick({R.id.tv_subtract, R.id.tv_add})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_subtract:
                subtractFontSize();
                break;
            case R.id.tv_add:
                addFontSize();
                break;
        }
    }


    //变大书本字体
    private void addFontSize() {
        if (currentFontSize < FONT_SIZE_MAX) {
            currentFontSize += 1;
            config.setFontSize(currentFontSize);
            pageFactory.changeFontSize(currentFontSize);
        }
    }

    //变小书本字体
    private void subtractFontSize() {
        if (currentFontSize > FONT_SIZE_MIN) {
            currentFontSize -= 1;
            config.setFontSize(currentFontSize);
            pageFactory.changeFontSize(currentFontSize);
        }
    }

    //改变亮度
    public void changeBright(Boolean isSystem, int brightness) {
        float light = (float) (brightness / 100.0);
        config.setSystemLight(isSystem);
        config.setLight(light);
        BrightnessUtil.setBrightness(ReadActivity.this, brightness);
    }


    @Override
    public void onBackPressed() {
        dealBeforeFinish();
        super.onBackPressed();
    }

    private void dealBeforeFinish() {
        long timeSeconds = (System.currentTimeMillis() - mStartTime) / 1000;
//        HttpMethod.readLong(this, new AnsynHttpRequest.ObserverCallBack() {
//            @Override
//            public void handleResult(String data, int encoding, int method) {
//
//            }
//        }, String.valueOf(timeSeconds), bookId, String.valueOf(begin), String.valueOf(percent));
        HttpMethod.videoPlaysPercent(this,null,bookId,String.valueOf(percent),String.valueOf(timeSeconds),"2",String.valueOf(begin));
        if(mIsBuy == 1){
            Intent intent = new Intent();
            intent.putExtra("percent", String.valueOf(percent));
            intent.putExtra("page", String.valueOf(begin));
            setResult(RESULT_OK, intent);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == RESULT_OK && REQUEST_ORDER_PAY == requestCode) {//支付成功
            if(mDialogFree!=null){
                mIsBuy = 1;
                mDialogFree.dismiss();
                setResult(RESULT_OK);
            }
        }
    }

    private void startPay(){
        boolean isLogin = MyApplication.getInstance().sputil.getBoolean(ConstantUserInfo.ISLOGIN);
        if (!isLogin) {
            dialogConfirm(null, null, null, null).show();
            return;
        }
        List<HotRankingBean.RankingBean> checkShopsData = new ArrayList<>();
        HotRankingBean.RankingBean mBookBean = new HotRankingBean.RankingBean();
        mBookBean.setId(bookId);
        mBookBean.setType(2);
        mBookBean.setTitle(bookName);
        mBookBean.setImg(bookCoverUrl);
        mBookBean.setAbstractX(bookDesc);
        checkShopsData.add(mBookBean);
        Bundle bundle = new Bundle();
        bundle.putSerializable("checkShops", (Serializable) checkShopsData);
        bundle.putString("shopsId",bookId);
        bundle.putString("categoryType","BookDetail");
        try {
            bundle.putFloat("payMoney",Float.parseFloat(mPayMoney));
        }catch (Exception e){}
        startActivityForResult(PayOrderActivity.class, bundle, REQUEST_ORDER_PAY);
    }
}
